﻿using System;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Abp.AspNetCore;
using Abp.AspNetCore.Configuration;
using Abp.AspNetCore.Mvc.Results;
using Abp.AspNetCore.SignalR;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Runtime.Caching.Redis;
using Abp.Zero.Configuration;
using pandx.Mulan.Authentication.JwtBearer;
using pandx.Mulan.Configuration;
using pandx.Mulan.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using pandx.Mulan.Folders;

namespace pandx.Mulan
{
    [DependsOn(
        typeof(MulanApplicationModule),
        typeof(MulanEntityFrameworkModule),
        typeof(AbpAspNetCoreModule),
        typeof(AbpAspNetCoreSignalRModule)
       
    )]
    public class MulanWebCoreModule : AbpModule
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        public MulanWebCoreModule(IWebHostEnvironment env)
        {
            _env = env;
            _appConfiguration = env.GetAppConfiguration();
        }

        public override void PreInitialize()
        {
            Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString(
                CoreConsts.ConnectionStringName
            );

           
            Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();
          
            Configuration.Modules.AbpAspNetCore()
                .CreateControllersForAppServices(
                    typeof(MulanApplicationModule).GetAssembly()
                );

            if (_appConfiguration["Authentication:JwtBearer:IsEnabled"] != null &&
                bool.Parse(_appConfiguration["Authentication:JwtBearer:IsEnabled"]))
            {
                ConfigureTokenAuth();
            }


            Configuration.ReplaceService(typeof(IAppConfigurationAccessor),
                () =>
                {
                    IocManager.Register(typeof(IAppConfigurationAccessor), typeof(AppConfigurationAccessor),
                        DependencyLifeStyle.Singleton);
                });
            Configuration.ReplaceService(typeof(IAppConfigurationWriter),
                () =>
                {
                    IocManager.Register(typeof(IAppConfigurationWriter), typeof(AppConfigurationWriter),
                        DependencyLifeStyle.Singleton);
                });
        }

        private void ConfigureTokenAuth()
        {
            IocManager.Register<TokenAuthConfiguration>();
            var tokenAuthConfig = IocManager.Resolve<TokenAuthConfiguration>();

            tokenAuthConfig.SecurityKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(_appConfiguration["Authentication:JwtBearer:SecurityKey"]));
            tokenAuthConfig.Issuer = _appConfiguration["Authentication:JwtBearer:Issuer"];
            tokenAuthConfig.Audience = _appConfiguration["Authentication:JwtBearer:Audience"];
            tokenAuthConfig.SigningCredentials =
                new SigningCredentials(tokenAuthConfig.SecurityKey, SecurityAlgorithms.HmacSha256);
            tokenAuthConfig.AccessTokenExpiration = AppConsts.AccessTokenExpiration;
            tokenAuthConfig.RefreshTokenExpiration = AppConsts.RefreshTokenExpiration;
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(MulanWebCoreModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            var appFolders = IocManager.Resolve<AppFolder>();
          

            appFolders.WebLogsFolder = Path.Combine(_env.ContentRootPath, $"logs");
            appFolders.BigFilesFolder = Path.Combine(_env.ContentRootPath, $"files{Path.DirectorySeparatorChar}big");
            appFolders.CommonFiesFolder = Path.Combine(_env.ContentRootPath, $"files{Path.DirectorySeparatorChar}common");
            appFolders.TempFolder = Path.Combine(_env.ContentRootPath, "temp");
            IocManager.Resolve<ApplicationPartManager>()
                .AddApplicationPartsIfNotAddedBefore(typeof(MulanWebCoreModule).Assembly);
        }
    }
}